using System;
using System.Collections.Generic;
using System.Linq;

using Azure.Infrastructure;

using Microsoft.WindowsAzure.StorageClient;

namespace Azure.Web.Stubs
{
    public class StubRepository<T> : IRepository<T> where T : TableServiceEntity
    {
        private static readonly List<T> Items = new List<T>();

        public IQueryable<T> Table
        {
            get { return Items.AsQueryable(); }
        }

        public void Attach(T existingItem)
        {
        }

        public void Delete(T itemToDelete)
        {
            Items.Remove(itemToDelete);
        }

        public void Insert(T newItem)
        {
            Items.Add(newItem);
        }

        public T Last()
        {
            var result = from p in Items orderby p.Timestamp select p;
            return result.Last();
        }

        public T Load(string partitionKey, string rowKey)
        {
            var result = from p in Items where p.PartitionKey == partitionKey && p.RowKey == rowKey select p;
            return result.First();
        }

        public IEnumerable<T> Load(string partitionKey)
        {
            return from p in Items where p.PartitionKey == partitionKey select p;
        }

        public IEnumerable<T> Query(IQueryable<T> query)
        {
            return query;
        }

        public IEnumerable<T> Last(int count)
        {
            return Items;
        }

        public void Update(T post)
        {
            var index = Items.FindIndex(y => y.PartitionKey == post.PartitionKey && y.RowKey == post.RowKey);
            Items[index] = post;
        }
    }
}